from typing import List, Dict, Any
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session

from app.core.database.connection import get_database
from app.domains.device.services import DeviceService
from app.domains.work_order.services import WorkOrderService
from app.domains.alert.services import AlertService
from app.shared.schemas.response import success_response, error_response
from app.shared.constants.status_codes import BusinessCode
from app.api.dependencies import get_current_user, check_resource_permission, ResourcePermission
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/dashboard", tags=["仪表盘"])


@router.get("/overview", response_model=dict, summary="获取系统概览数据")
async def get_system_overview(
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_view_reports, "无权限查看仪表盘"
    )),
    db: Session = Depends(get_database)
):
    """
    获取系统概览数据（管理员和经理可查看）
    
    包含设备、工单、告警的核心统计指标
    """
    try:
        device_service = DeviceService(db)
        work_order_service = WorkOrderService(db)
        alert_service = AlertService(db)
        
        # 获取各模块统计数据
        device_stats = device_service.get_dashboard_statistics()
        work_order_stats = work_order_service.get_statistics()
        alert_stats = alert_service.get_statistics()
        
        # 合并概览数据
        overview_data = {
            "devices": device_stats,
            "work_orders": work_order_stats,
            "alerts": alert_stats,
            "summary": {
                "total_devices": device_stats["devices"]["total"],
                "online_devices": device_stats["devices"]["online"],
                "pending_work_orders": work_order_stats["pending_count"],
                "unresolved_alerts": alert_stats["unresolved_count"],
                "critical_alerts": alert_stats["critical_count"]
            }
        }
        
        return success_response(
            data=overview_data,
            message="系统概览数据获取成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取系统概览数据异常: {e}")
        return error_response(
            message="获取系统概览数据失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/real-time", response_model=dict, summary="获取实时数据")
async def get_real_time_data(
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取实时数据（所有用户可查看）
    
    包含设备在线状态、最新告警等实时信息
    """
    try:
        device_service = DeviceService(db)
        alert_service = AlertService(db)
        
        # 获取在线设备数量
        device_stats = device_service.get_dashboard_statistics()
        online_device_count = device_stats["devices"]["online"]
        total_device_count = device_stats["devices"]["total"]
        
        # 获取最新未解决告警（前5个）
        from app.domains.alert.schemas import AlertListQuery
        alert_query = AlertListQuery(
            page=1,
            page_size=5,
            is_resolved=False,
            sort_by="created_at",
            sort_order="desc"
        )
        recent_alerts, _ = alert_service.get_alert_list(alert_query)
        
        # 获取最新工单（前5个）
        from app.domains.work_order.schemas import WorkOrderListQuery
        work_order_service = WorkOrderService(db)
        work_order_query = WorkOrderListQuery(
            page=1,
            page_size=5,
            sort_by="created_at",
            sort_order="desc"
        )
        recent_work_orders, _ = work_order_service.get_work_order_list(work_order_query)
        
        real_time_data = {
            "device_status": {
                "online_count": online_device_count,
                "total_count": total_device_count,
                "online_rate": round((online_device_count / total_device_count * 100), 1) if total_device_count > 0 else 0
            },
            "recent_alerts": [
                {
                    "id": alert.id,
                    "alert_number": alert.alert_number,
                    "title": alert.title,
                    "level": alert.level.value,
                    "alert_type": alert.alert_type.value,
                    "device_name": alert.device.device_name if alert.device else None,
                    "created_at": alert.created_at.isoformat()
                }
                for alert in recent_alerts
            ],
            "recent_work_orders": [
                {
                    "id": wo.id,
                    "work_order_number": wo.work_order_number,
                    "title": wo.title,
                    "status": wo.status.value,
                    "priority": wo.priority.value,
                    "device_name": wo.device.device_name if wo.device else None,
                    "created_at": wo.created_at.isoformat()
                }
                for wo in recent_work_orders
            ]
        }
        
        return success_response(
            data=real_time_data,
            message="实时数据获取成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取实时数据异常: {e}")
        return error_response(
            message="获取实时数据失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/trends", response_model=dict, summary="获取趋势数据")
async def get_trend_data(
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_view_reports, "无权限查看趋势数据"
    )),
    db: Session = Depends(get_database)
):
    """
    获取趋势数据（管理员和经理可查看）
    
    包含设备状态变化、工单处理趋势、告警趋势等
    """
    try:
        from datetime import datetime, timedelta
        from sqlalchemy import func
        from app.domains.models import Device, WorkOrder, Alert
        
        # 获取最近7天的数据
        end_date = datetime.utcnow().date()
        start_date = end_date - timedelta(days=6)
        
        # 工单趋势（按天统计）
        work_order_trend = []
        for i in range(7):
            date = start_date + timedelta(days=i)
            count = db.query(WorkOrder).filter(
                func.date(WorkOrder.created_at) == date
            ).count()
            work_order_trend.append({
                "date": date.isoformat(),
                "count": count
            })
        
        # 告警趋势（按天统计）
        alert_trend = []
        for i in range(7):
            date = start_date + timedelta(days=i)
            count = db.query(Alert).filter(
                func.date(Alert.created_at) == date
            ).count()
            alert_trend.append({
                "date": date.isoformat(),
                "count": count
            })
        
        trend_data = {
            "work_order_trend": work_order_trend,
            "alert_trend": alert_trend,
            "date_range": {
                "start_date": start_date.isoformat(),
                "end_date": end_date.isoformat()
            }
        }
        
        return success_response(
            data=trend_data,
            message="趋势数据获取成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取趋势数据异常: {e}")
        return error_response(
            message="获取趋势数据失败",
            code=BusinessCode.OPERATION_FAILED
        )